const {
  MemberModel
} = require('../../../utils/member-model.js');
var memberModel = new MemberModel();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    layerContent: false, //微信预留手机号和店面预留手机号不一致的提示 
    layerCard: false, //二次绑卡 
    layerCardHtml: "",
    disabled: true,
    codeDisabled: false,
    cardNo: "", //卡号 
    phone: "", //手机号 
    validCode: "", //验证码 
    shopId: "", //门店id 
    wechatPhone: "", //微信预留手机号 
    cardReservedPhone: "", //店面预留手机号 
    codeHtml: "获取验证码", //获取验证码按钮 
    second: false, //是否为第二次绑卡，第二次则不需要验证码 
    cancelCardNo: "", //注销卡卡号
    cancelCardNoHtml: "", //注销卡卡号
    layerError: false, //错误信息弹出层
    layerErrorTitle: "", //错误信息
    checkPhone: true, //校验卡号和手机号是否一致
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},
  /**
   * 绑卡
   */
  bindCard: function () {
    if (this.data.checkPhone) {
      wx.reportAnalytics('bindcard_submit')
      var param = {};
      param.merchantId = wx.getStorageSync('merchantId');
      param.cardNo = this.data.cardNo; //卡号 
      param.shopId = this.data.shopId; //门店id 
      param.phone = this.data.phone; //手机号 
      if (!this.data.second) {
        param.validCode = this.data.validCode; //验证码 
      }
      param.logoutCardNo = this.data.cancelCardNo; // 同门店旧卡
      param.second = this.data.second //是否为第二次绑卡，第二次则不需要验证码 
      memberModel.userCardBinding(param).then(data => {
        var paramPhone = param.phone;
        if (this.data.wechatPhone != "") {
          paramPhone = this.data.wechatPhone
        } else {
          paramPhone = param.phone
        }
        wx.redirectTo({
          url: '/pages/memberCenter/bindingSuccess/index?phone=' + paramPhone
        })
      }).catch(err => {
        if (err.errorCode == "2003") {
          var cardNo = err.error;
          var cancelCardNoHtml = cardNo.substring(cardNo.length - 6);
          var layerCardHtml = '是否注销卡号:' + cancelCardNoHtml + '(会员卡号后6位),绑定新卡？'
          if (cardNo == param.cardNo) {
            layerCardHtml = '您已有SVIP会员卡，卡号（后六位' + cancelCardNoHtml + '),资产合并到会员账户后将注销。'
          }
          this.setData({
            layerCard: true,
            layerCardHtml: layerCardHtml,
            cancelCardNo: cardNo,
            cancelCardNoHtml: cardNo.substring(cardNo.length - 6),
          })
        } else {
          this.setErrorLayer(err.error); //设置错误信息
        }
      })
    } else {
      this.setData({
        layerContent: true
      });
    }
  },
  /** 
   * 注销卡 
   */
  setUserCardLogout: function () {
    wx.reportAnalytics('bindcard_loginout')
    // var param = {};
    // param.cardNo = this.data.cancelCardNo; //注销卡卡号 
    // param.newCardNo = this.data.cardNo; //新绑定会员卡卡号
    // param.shopId = this.data.shopId; //门店id 
    // memberModel.userCardLogout(param).then(data => {
    this.setData({
      second: true
    }, function () {
      this.bindCard(); //二次绑卡 
    })
    // }).catch(err => {
    //   this.setData({
    //     layerCard: false,
    //   });
    //   this.setErrorLayer(err.error); //设置错误信息
    // })
  },



  /**
   * 获取验证码验证
   * */
  getValidCode: function () {
    var res = /^1\d{10}$/;
    var resCard = /[^\w\.\/]/ig;
    if (this.data.cardNo == "") {
      wx.showToast({
        title: `请输入会员卡号！`,
        icon: 'none',
        duration: 2000
      })
    } else if (resCard.test(this.data.cardNo)) {
      wx.showToast({
        title: `卡号错误，请重新输入`,
        icon: 'none',
        duration: 2000
      })
    } else if (this.data.phone == "") {
      wx.showToast({
        title: `请输入手机号！`,
        icon: 'none',
        duration: 2000
      })
    } else if (this.data.phone.length != 11 || !res.test(this.data.phone)) {
      wx.showToast({
        title: `请输入正确的手机号！`,
        icon: 'none',
        duration: 2000
      })
    } else {
      wx.reportAnalytics('bindcard_getcode')
      this.getUserCardInfo(); //获取验证码
    }
  },
  /**
   * 调取获取验证码接口
   */
  getUserCardInfo: function () {
    var param = {};
    param.merchantId = wx.getStorageSync('merchantId')
    param.cardNo = this.data.cardNo //卡号 
    param.phone = this.data.phone //手机号 
    memberModel.userVerificationCode(param).then(data => {
      this.setData({
        codeDisabled: true,
        shopId: data.cardInfo.shopId || "",
        wechatPhone: data.cardInfo.wechatPhone || "",
        cardReservedPhone: data.cardInfo.cardReservedPhone || "",
        cardNo: data.cardInfo.cardNo || ""
      }, function () {
        if (data.cardInfo.wechatPhone != data.cardInfo.cardReservedPhone) {
          this.setData({
            checkPhone: false
          })
        } else {
          this.setData({
            checkPhone: true
          })
        }
        this.startReportHeart(); //倒计时 
      })
    }).catch(err => {
      this.setErrorLayer(err.error); //设置错误信息
    })
  },

  /**
   * 设置输入的值
   */
  setValue: function (e) {
    var that = this;
    var value = e.detail.value;
    var type = e.currentTarget.dataset.id;
    var resCard = /[^a-zA-Z0-9]/g;
    if (type == "cardNo") {
      if (resCard.test(value)) {
        this.setData({
          cardNo: this.data.cardNo
        }, function () {
          that.checkInfo();
        })
      } else {
        this.setData({
          cardNo: value
        }, function () {
          that.checkInfo();
        })
      }
    } else if (type == "phone") {
      this.setData({
        phone: value
      }, function () {
        that.checkInfo();
      })
    } else if (type == "code") {
      this.setData({
        validCode: value
      }, function () {
        that.checkInfo();
      })
    }
  },

  /**
   * 验证输入的内容
   */
  checkInfo: function () {
    var that = this;
    var t = true;
    var res = /^1\d{10}$/;
    var resCard = /[^a-zA-Z0-9]/g;
    if (that.data.cardNo != "" && that.data.phone != "" && that.data.phone.length == 11 && res.test(that.data.phone) && that.data.validCode != "" && !resCard.test(that.data.cardNo)) {
      that.setData({
        disabled: false,
      })
    } else {
      that.setData({
        disabled: true,
      })
    }

  },

  /** 
   * 计时器 
   */
  startReportHeart: function () {
    var time = 60;
    var that = this;
    var timerTem = setInterval(function (e) {
      time--;
      that.setData({
        codeHtml: time + "S"
      })
      if (time == 0)
        clearInterval(timerTem),
        that.setData({
          codeDisabled: false,
          codeHtml: "重新获取"
        })
    }, 1000)
  },

  /** 
   * 关闭弹出层 
   */
  closeLayerContent: function () {
    this.setData({
      layerContent: false,
    });
  },

  /** 
   * 二次绑卡确认
   */
  setLayerContent: function () {
    wx.reportAnalytics('bindcard_ensure')
    this.setData({
      layerContent: false,
      checkPhone: true
    }, function () {
      this.bindCard(); //二次绑卡 
    });
  },
  /** 
   * 关闭二次绑卡弹出层 
   */
  closeLayerCard: function () {
    this.setData({
      layerCard: false
    });
  },
  /**
   * 错误信息
   */
  setErrorLayer: function (error) {
    var that = this;
    that.setData({
      layerError: true,
      layerErrorTitle: error,
    })
    var timerTem = setTimeout(function () {
      that.setData({
        layerError: false,
        layerErrorTitle: ""
      })
      clearTimeout(timerTem);
    }, 2000, '')
  }
})